package com.hnl.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hnl.core.HNLPageDispatch;
import com.hnl.core.aware.HNLAuthAware;

public class UserAuthenticationFilter implements Filter, HNLAuthAware,
		HNLPageDispatch {
	public static final Logger LOG = LoggerFactory
			.getLogger(UserAuthenticationFilter.class);
	private String[] excludePatternArray;

	private final String LOGIN_ERROR = "Your session has timed out. Please login again.";

	private FilterConfig fc;

	@Override
	public void destroy() {
		// Any Cleanup TODO?
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		boolean exclude = false;
		if (req instanceof HttpServletRequest) {
			HttpServletRequest hreq = (HttpServletRequest) req;
			for (String excludePattern : excludePatternArray) {
				if (hreq.getRequestURI().matches(excludePattern)) {
					exclude = true;
				}
			}
			if (exclude == false) {
				HttpSession session = ((HttpServletRequest) req).getSession();
				if (session.getAttribute(ATTRIBUTE_USER) == null) {
					RequestDispatcher dispatcher = req
							.getRequestDispatcher(LOGIN_PAGE);
					req.setAttribute("error", LOGIN_ERROR);
					dispatcher.forward(req, resp);
					return;
				}
			}
		}
		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.fc = config;
		String excludePatternArray = fc.getInitParameter("excludeRegExPattern");
		setExcludePatternArray(excludePatternArray.split(","));
	}

	public String[] getExcludePatternArray() {
		return excludePatternArray;
	}

	public void setExcludePatternArray(String[] excludePattern) {
		this.excludePatternArray = excludePattern;
	}

}
